package pro.ticktock.tools.xwpf;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import pro.ticktock.tools.mbconv.Pass2;
import pro.ticktock.tools.mbconv.Pass6;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * Author: lambo
 * Date: 2018-09-27
 */
public class MakeDoc {
  public static void main(String[] args) throws Exception {
    //Blank Document
    XWPFDocument document = new XWPFDocument();
    CTDocument1 ct1 = document.getDocument();
    CTBody body = ct1.getBody();
    if (!body.isSetSectPr()) {
      body.addNewSectPr();
    }
    CTSectPr pr = body.getSectPr();
    if (!pr.isSetPgMar()) {
      pr.addNewPgMar();
    }

    CTPageMar pmar = pr.getPgMar();
    pmar.setLeft(new BigInteger("1200", 10));
    pmar.setRight(new BigInteger("1200", 10));
    pmar.setTop(new BigInteger("800", 10));
    pmar.setBottom(new BigInteger("800", 10));

    if (!pr.isSetCols()) {
      pr.addNewCols();
    }
    CTColumns cols = pr.getCols();
    cols.setNum(new BigInteger("2", 10));
    //dfts.set

    //Write the Document in file system
    FileOutputStream out = new FileOutputStream( new File("doc1.docx"));
    /*
    //create paragraph
    XWPFParagraph paragraph = document.createParagraph();

    //Set Bold an Italic
    XWPFRun paragraphOneRunOne = paragraph.createRun();
    paragraphOneRunOne.setBold(true);
    paragraphOneRunOne.setItalic(true);
    paragraphOneRunOne.setText("Font Style");
    paragraphOneRunOne.addBreak();

    //Set text Position
    XWPFRun paragraphOneRunTwo = paragraph.createRun();
    paragraphOneRunTwo.setText("Font Style two");
    paragraphOneRunTwo.setTextPosition(100);

    //Set Strike through and Font Size and Subscript
    XWPFRun paragraphOneRunThree = paragraph.createRun();
    paragraphOneRunThree.setStrike(true);
    paragraphOneRunThree.setFontSize(20);
    paragraphOneRunThree.setSubscript(VerticalAlign.SUBSCRIPT);
    paragraphOneRunThree.setText(" Different Font Styles");
    */

    Path path = Paths.get(MakeDoc.class.getClassLoader()
            .getResource("long.txt").toURI());
    final String fontHei = "黑体";
    final String fontSong = "宋体";
    final String fontKai = "楷体";
    AtomicBoolean isArt = new AtomicBoolean(false);
    Pattern p = Pattern.compile(Pass6.LIST_MARK);
    Files.readAllLines(path).stream().forEach(line -> {
      line = line.replace(Pass6.NUMBER_NA_MARK, "");
      line = line.replace(Pass6.LEADING_LIST_MARK, "");
      Matcher m = p.matcher(line);
      int lastEnd = 0;
      StringBuffer sb = new StringBuffer();
      int cnt = 1;
      while (m.find()) {
        sb.append(line.substring(lastEnd, m.start()));
        sb.append(cnt++).append(". ");
        lastEnd = m.end();
      }
      sb.append(line.substring(lastEnd));
      line = sb.toString();

      XWPFParagraph para = document.createParagraph();

      XWPFRun run = para.createRun();

      if (line.startsWith(Pass2.CH_TITLE_MARK)) {
        line = line.substring(Pass2.CH_TITLE_MARK.length());
        run.setBold(true);
        run.setFontSize(12);
        run.setFontFamily(fontHei);
        isArt.set(false);
        para.setSpacingBefore(100);
      } else if (line.startsWith(Pass2.EN_TITLE_MARK)) {
        para.setAlignment(ParagraphAlignment.CENTER);
        line = line.substring(Pass2.EN_TITLE_MARK.length());
        run.setFontSize(12);
        para.setSpacingAfter(100);
        run.setFontFamily(fontSong);
        isArt.set(false);
      } else if (line.startsWith(Pass2.CH_ARTIST_MARK)) {
        line = line.substring(Pass2.CH_ARTIST_MARK.length());
        run.setBold(true);
        run.setFontSize(12);
        run.setFontFamily(fontHei);
        para.setSpacingBefore(100);
        run.setFontFamily(fontSong);
        isArt.set(true);
      } else if (line.startsWith(Pass2.EN_ARTIST_MARK)) {
        para.setAlignment(ParagraphAlignment.CENTER);
        line = line.substring(Pass2.EN_ARTIST_MARK.length());
        run.setFontSize(12);
        para.setSpacingAfter(100);
        isArt.set(true);
      } else {
        if (isArt.get()) {
          run.setFontFamily(fontKai);
        } else {
          run.setFontFamily(fontSong);
        }
        line = "　　" + trim(line);
      }
      run.setText(line);
    });

    document.write(out);
    out.close();
    System.out.println("createdocument.docx written successully");
  }

  static String trim(String str) {
    str = str.trim();
    if (str.length() == 0) return str;
    int i = 0;
    while(i < str.length() && str.charAt(i++) == '　');
    return str.substring(i - 1);
  }
}
